﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FlowBasis.Json;
using System.Collections;

namespace FlowBasis.Data
{
    public static class JObjectResultSetHelper
    {
        public static JObjectResultSet ToJObjectResultSet<T>(
            this IQueryable<T> query,
            int? offset,
            int? maxResults,
            Func<T, object> dataConverter)
        {
            int overallCount = query.Count();

            var limitedQuery = query;
            if (offset.HasValue)
                limitedQuery = limitedQuery.Skip(offset.Value);

            if (maxResults.HasValue)
                limitedQuery = limitedQuery.Take(maxResults.Value);
            
            ArrayList itemList = new ArrayList();

            foreach (var item in query)
            {
                object itemData = dataConverter(item);
                itemList.Add(itemData);
            }

            JObjectResultSet resultSet = new JObjectResultSet();

            resultSet.Data = itemList;

            if (offset.HasValue)
                resultSet.Offset = offset.Value;
            else
                resultSet.Offset = 0;

            resultSet.OverallCount = overallCount;

            return resultSet;
        }
    }
}
